package client;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.InputMismatchException;

import javax.swing.text.DateFormatter;

public class CommandClient {

	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd:HH:mm:ss");
	protected Scanner keyboard;

	public CommandClient() {
		keyboard = new Scanner(System.in);	
	}
	
	public String prompt(String prompt) {
		String result = "";
		while (result.length() == 0) {
			System.out.println(prompt);
			result = keyboard.nextLine();
		}
		return result;
	}
	
	public int promptInt(String prompt) {
		while (true) {
			System.out.println(prompt);
			try {
				int number = keyboard.nextInt();
				keyboard.nextLine();
				return number;
			} catch (InputMismatchException e) {
				continue;
			}
		}
	}
	
	public int promptChoice(String prompt, int numberOfChoices) {
		int choice = 0;
		while (choice == 0 || choice >= numberOfChoices + 1) {
			choice = promptInt(prompt);
		}
		return choice;
	}
	
	public int promptMenu(String title, String prompt, String... items) {
		printTitle(title);
		for (int i = 0; i < items.length; i++) {
			System.out.println("[" + (i + 1) + "] " + items[i]);
		}
		String choicePrompt = " (1-" + items.length + ")";
		return promptChoice(prompt + choicePrompt, items.length);
	}
	
	
	public void showHeader(String title) {
		printRepeatedLine('=', title.length() + 4);
		System.out.println("  " + title + "  ");
		printRepeatedLine('=', title.length() + 4);
	}

	public void printToLog(String message, String name){
		System.out.println("[Log] " + message);
		String filename = "client." + name + ".log";
		String logString = dateFormat.format(new Date()) + " " + message + "\n";
		try (BufferedWriter out = new BufferedWriter(new FileWriter(filename, true))) {
			out.write(logString);
		} catch (IOException e){
			e.printStackTrace();
		}
	}
	
	public void printTitle(String title) {
		System.out.println();
		System.out.println(title);
		printRepeatedLine('-', title.length());
	}

	
	public void printRepeatedLine(char c, int times) {
		for (int i = 0; i < times; i++) {
			System.out.print(c);
		}
		System.out.println();
	}
	
	public void waitForEnter() {
		System.out.println("Press Enter to continue.");
		keyboard.nextLine();
	}
	
	public static void printHeader(String title) {
		int w = 70;
		System.out.println();
		int padding = (w - title.length()) / 2;
		for (int i = 0; i < w; i++) {
			System.out.print("=");
		}
		System.out.println();
		for (int i = 0; i < padding; i++) {
			System.out.print(" ");
		}
		System.out.println(title.toUpperCase());
		for (int i = 0; i < w; i++) {
			System.out.print("=");
		}

		System.out.println();
		System.out.println();
	}
}
